<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker 
         v-model="dateRange" 
         value-format="YYYY-MM-DD" 
         type="daterange" 
         range-separator="-" 
         start-placeholder="开始日期" 
         end-placeholder="结束日期">
        </el-date-picker> 
      </el-form-item>
      <!-- <el-form-item label="机器编号" prop="innerCode">
        <el-input
          v-model="queryParams.innerCode"
          placeholder="请输入机器编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['manage:order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" prop="id" />
      <el-table-column label="订单编号" align="center" prop="orderNo" >
        <template #default="scope">
            {{ scope.row.orderNo}}
        </template>
      </el-table-column>
      <el-table-column label="商品名称"  width="90"  align="center" prop="skuName" />
      <el-table-column label="支付金额"  width="80"  align="center" prop="amount" />
      <el-table-column label="设备编号"  width="90"  align="center" prop="innerCode" />
      <el-table-column label="订单状态"  align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单日期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{d}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="getOrderDetail(scope.row)" v-hasPermi="['manage:order:query']">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" v-model="orderOpen" width="800px" append-to-body class="custom-dialog">
      <el-form ref="orderRef" :model="_orderDetail" :rules="rules" label-width="50px" class="custom-form" >
          <el-row class="form-row" >
            <el-col :span="12" class="form-col">
              <div class="form-label">订单编号：</div>
              <div class="form-value">{{ _orderDetail.id }}</div>
            </el-col>
            <el-col :span="12" class="form-col">
              <div class="form-label">商品名称：</div>
              <div class="form-value">{{ _orderDetail.skuName }}</div>
            </el-col>
          </el-row>
           <el-row class="form-row">
            <el-col :span="12" class="form-col">
              <div class="form-label">订单金额：</div>
              <div class="form-value">{{ _orderDetail.price }}</div>
            </el-col>
            <el-col :span="12" class="form-col">
              <div class="form-label">订单状态：</div>
              <div class="form-value">
                <dict-tag :options="order_status" :value="_orderDetail.status"/> 
              </div>
            </el-col>
          </el-row>
          <el-row class="form-row">
            <el-col :span="12" class="form-col">
              <div class="form-label">设备编号：</div>
              <div class="form-value">{{ _orderDetail.innerCode }}</div>
            </el-col>
            <el-col :span="12" class="form-col">
              <div class="form-label">设备地址：</div>
              <div class="form-value">{{ _orderDetail.Vmaddr }}</div>
            </el-col>
          </el-row>
           <el-row class="form-row">
            <el-col :span="12" class="form-col">
              <div class="form-label">创建时间：</div>
              <div class="form-value">{{ _orderDetail.createTime }}</div>
            </el-col>
            <el-col :span="12" class="form-col">
              <div class="form-label">完成时间：</div>
              <div class="form-value">{{ _orderDetail.updateTime }}</div>
            </el-col>
          </el-row>
          <el-row class="form-row" v-if="_orderDetail.status!=0">
            <el-col :span="12" class="form-col">
              <div class="form-label">支付方式：</div>
              <div class="form-value">
                <dict-tag :options="order_pay_type" :value="_orderDetail.payType"/> 
              </div>
            </el-col>
            <el-col :span="12" class="form-col">
              <div class="form-label">交易单号：</div>
              <div class="form-value">{{ _orderDetail.orderNo }}</div>
            </el-col>
          </el-row>
          <el-row class="form-row" v-if="_orderDetail.status != 4">
            <el-col :span="12" class="form-col">
              <div class="form-label">操作：</div>
              <div class="form-value" v-if="_orderDetail.status!=0 ">
                <el-button @click="submitForm">退款</el-button>
              </div>
              <div class="form-value" v-else="_orderDetail.status==0">
                <el-button  @click="cancelOrder(_orderDetail)">取消订单</el-button>
              </div>
            </el-col>
             
          </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--修改订单确认对话框-->
    <!-- <el-dialog title="订单取消确认" v-model="cancelOrderOpen" width="30%" append-to-body class="custom-dialog">
      <div class="dialog-body">
        <div class="dialog-body-text">确定取消该订单？</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancelOrder">确 定</el-button>
          <el-button type="primary" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/manage/order";
import { onActivated, ref } from "vue";
import {getVmByInnerCode} from "@/api/manage/vm";

const { proxy } = getCurrentInstance();
const { order_pay_status, order_status, order_pay_type } = proxy.useDict('order_pay_status', 'order_status', 'order_pay_type');

const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    innerCode: null,
    skuName: null,
    classId: null,
    status: null,
    payType: null,
    payStatus: null,
    regionId: null,
    partnerId: null,
    nodeId: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

onActivated(() => {
  const time = route.query.t;
  console.log('route.query:',route.query);
  
  console.log('time:',time);
  
  if (time != null && time != uniqueId.value){
    uniqueId.value = time;
    queryParams.value.pageNum = Number(route.query.pageNum);
    dateRange.value = [];
    proxy.resetForm("queryForm");
    getList();
  }
})

import { addDateRange } from "../../../utils/ruoyi"; 
/** 查询订单管理列表 */
function getList() {
  loading.value = true;
  const params = addDateRange(queryParams.value, dateRange.value);
  // console.log('params:',params);
  
  listOrder(params).then(response => {
    orderList.value = response.rows;
    //查看order List数据中的每一个对象
    orderList.value.forEach(item => {
      //将支付类型根据数据库的code值进行转换
      item.payType ==="wxpay" ? item.payType = 2 : item.payType = 1;
    });
    // console.log('orderList:',orderList.value);
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  orderOpen.value = false;
  orderDetailList = [];
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    thirdNo: null,
    innerCode: null,
    channelCode: null,
    skuId: null,
    skuName: null,
    classId: null,
    status: null,
    amount: null,
    price: null,
    payType: null,
    payStatus: null,
    bill: null,
    addr: null,
    regionId: null,
    regionName: null,
    businessType: null,
    partnerId: null,
    openId: null,
    nodeId: null,
    nodeName: null,
    cancelDesc: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("orderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log('dateRange:', dateRange.value);
  console.log('queryParams:', queryParams.value);
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加订单管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  orderUpdateOpen.value = true;
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          orderOpen.value = false;
          getList();
        });
      } else {
        addOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          orderOpen.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除订单管理编号为"' + _ids + '"的数据项？').then(function() {
    return delOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

//定义一个开关，控制订单详情对话框
const orderOpen = ref(false);
//定义一个对象，接收订单详情数据
const _orderDetail = ref({});
/** 查看订单详情  */
function getOrderDetail(row){
  const _id = row.id;
  getOrder(_id).then(response => {
    _orderDetail.value = response.data;
    //查看_orderDetail的数据
    _orderDetail.value.payType ==="wxpay" ? _orderDetail.value.payType = 2 : _orderDetail.value.payType = 1;
    getVmAddr(row.innerCode);
    
    title.value = "订单详情";
    orderOpen.value = true;
    // console.log(_orderDetail.value);
  });
  
}

/** 根据innerCode查询设备地址 */
function getVmAddr(innerCode){
  getVmByInnerCode(innerCode).then(response => {
    // console.log('getVmAddr方法：response:',response);
    //将设备的地址添加到_orderDetail中
    _orderDetail.value.Vmaddr = response.data.addr;
  }).catch(error => {
    console.log('error:',error);
  })
}

//定义一个对象，用来存储取消订单的参数
const _cancelOrder = ref({});
//定义一个函数，用来控制取消订单按钮后，将订单状态设置成已取消
function cancelOrder(row){
  const _id = Number(row.id);//将_id转换成Number类型；
  _cancelOrder.value = {
    id: _id,
    status: 4
  };
  proxy.$modal.confirm('是否确认取消订单编号为"' + _id + '"的订单？').then(function() {
    return updateOrder(_cancelOrder.value);
  }).then(() => {
    getList();
    getOrderDetail(row);
    proxy.$modal.msgSuccess("取消成功");
  }).catch(() => {});
}

getList();
</script>


<style scoped>
/* 对话框样式 */
.custom-dialog {
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

.custom-dialog .el-dialog__header {
  background-color: #007bff;
  color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  padding: 15px;
  font-size: 18px;
  font-weight: bold;
}

.custom-dialog .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

/* 表单样式 */
.custom-form {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 5px;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.form-row {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.form-col {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  flex: 1;
  margin-right: 10px;
}

.form-col:last-child {
  margin-right: 0;
}

.form-col:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.form-label {
  font-weight: bold;
  margin-right: 10px;
  color: #333;
  flex: 1;
}

.form-value {
  color: #666;
  flex: 1;
}
</style>